package com.inspur.edp.common.expr.expresses.node;

import com.inspur.edp.common.expr.Express;
import com.inspur.edp.common.expr.ExpressDSLGenerator;
import com.inspur.edp.common.expr.ast.ASTContext;
import com.inspur.edp.common.expr.ast.CompileUnitParser;
import com.inspur.edp.common.expr.parser.ASTParser;
import com.inspur.edp.common.expr.parser.ExpressAstParser;
import com.inspur.edp.common.type.TypeRefer;

import java.util.List;

/**
 * @author lizhaorui
 * @date 2025/9/15
 * @description
 */
public class NodeVariableDSL implements ExpressDSLGenerator {

    @Override
    public String getKind() {
        return NodeVariableExpr.KIND;
    }

    @Override
    public String generate(ASTContext context, Express express) {
        NodeVariableExpr nodeVariableExpr = (NodeVariableExpr) express;
        StringBuilder sb = new StringBuilder();
        sb.append(nodeVariableExpr.getNodeCode());
        sb.append(".");
        sb.append(nodeVariableExpr.getVariable());
        List<String> fields = nodeVariableExpr.getFields();
        if (fields != null && fields.size() != 0) {
            String lastFieldCode = "";
            for (String fieldCode : fields) {
                sb.append(".");
                sb.append(fieldCode);
                lastFieldCode = fieldCode;
            }
            String path = sb.toString();
            String objectPath = path.substring(0, path.length() - lastFieldCode.length() - 1);
            CompileUnitParser.ExpressContext objectExpressContext = ASTParser.parse(objectPath).express();
            TypeRefer objectType = ExpressAstParser.getOriginalType(objectExpressContext, context);
            if (objectType.isList()) {
                String listUtilsUrl = "com.inspur.edp.rule.dsl.core.function.list.ListUtils";
                context.addImport(listUtilsUrl);
                return String.format("ListUtils.getFieldStrings(%s,\"%s\")", objectPath, lastFieldCode);
            } else {
                return sb.toString();
            }
        } else {
            return sb.toString();
        }
    }
}